package com.lx.spring.jdbc.biz;

import com.lx.spring.biz.BizException;
import com.lx.spring.jdbc.dao.AccountDao;
import com.lx.spring.jdbc.dao.OperCordDao;
import com.lx.spring.jdbc.entity.Account;
import com.lx.spring.jdbc.entity.OperCord;
import com.lx.spring.mvc.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


//业务层
@Service
public class BankBiz {

    // 存款(deposit), 取款(withdraw), 转账(transfer), 开户(register), 查询(query)
    @Autowired
    AccountDao aDao;
    @Autowired
    OperCordDao oDao;

    //配置事务
    @Transactional(rollbackFor = BizException.class,
                    //rollbackFor 编译时异常 默认提交
                    //noRollbackFor 运行时异常 默认不提交
                    noRollbackFor = ArithmeticException.class)
    //存款(deposit)
    public void deposit(long id, double money) throws BizException {
        OperCord o = new OperCord();
        o.setAid(id);
        o.setOpMoney(money);
        oDao.insert(o);
        /*if(money > 5000){
            //编译时异常
            throw new BizException("存款大于5000");
        }*/
        //运行时异常
//        int i = 1 / 0;
        aDao.updateBalanceById(id, money);

    }

    //取款(withdraw)
    public void withdraw(long id, double money){

    }

    //转账(transfer)
    @Transactional(rollbackFor = BizException.class, noRollbackFor = ArithmeticException.class)
    public Result transfer(long id1, long id2, double money){
        double balance = aDao.queryBalanceById(id1);
        if(balance < money){
            return new Result(0, "余额不足", null);
        }
        Account account2 = aDao.queryById(id2);
        aDao.updateBalanceById(id1, -money);
        OperCord o = new OperCord();
        o.setAid(id1);
        o.setOpMoney(money);
        o.setRemark("转账");
        oDao.insert(o);
        aDao.updateBalanceById(id2, money);

        return new Result(1, "转账成功", null);
    }


}
